﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Srvtools;

public partial class WorkTime_ViewEmpWorkOn : System.Web.UI.Page
{
    private Hashtable EmpWorkOnDateTable;
    private Hashtable CompWorkDateDefine;
    private Hashtable EmpOverTimeDateTable;

    private string StartWorkOn;
    private string EndWorkOn;
    private string LateOfStartTime;
    private string LeaveOfEndTime;

    private DateTime FirstDayOfThisMonth;
    private DateTime LastDayOfThisMonth;
    string EmpId = "";

    protected void Page_Load(object sender, EventArgs e)
    {

        string TheYear = "";
        string TheMonth = "";
        string sEmpId = "";
        string sSelf = "";

        //输入变量的定义 EId=1(是否可选择人员是=0,144(工号),2008(年),2(月)
        if (this.Request.QueryString["ItemParam"].IndexOf("EId") != -1)
        {
            String Inv = this.Request.QueryString["ItemParam"].ToString().Replace("EId=", "");
            string[] Temp = Inv.Split(new char[1] { ',' });

            if (Temp[0] == "1")
            {
                sSelf = Temp[0];
                sEmpId = int.Parse(Temp[1]).ToString();
                if (sEmpId == "0") sEmpId = "";
                TheYear = Temp[2];
                if (TheYear == "0") TheYear = "";
                TheMonth = Temp[3];
                if (TheMonth == "0") TheMonth = "";
            }
            else
            {
                sEmpId = Srvtools.CliUtils.GetValue("_UserCode")[1].ToString();
                sEmpId = int.Parse(sEmpId).ToString();
                sSelf = "0";
            }
        }
        else
        {
            return;
        }

        //
        if (!IsPostBack)
        {
            if (sEmpId.Length > 0)
            {
                SelUser.ReadOnly(sEmpId, Srvtools.CliUtils.fUserName);
               //WebRefVal1.BindingValue = sEmpId;
                //EmpId = sEmpId;
                
            }
            else
            {
                sEmpId = Srvtools.CliUtils.GetValue("_UserCode")[1].ToString();
                EmpId = int.Parse(sEmpId).ToString();
                //WebRefVal1.BindingValue = EmpId;
                SelUser.SelUserInti(sEmpId, Srvtools.CliUtils.fUserName);
                
            }

            if (TheYear.Length > 0 && TheMonth.Length > 0)
            {
                DateTime Std = new DateTime(int.Parse(TheYear), int.Parse(TheMonth), 1);
                Calendar1.VisibleDate = Std;
            }

            //
            //if (sSelf == "1")
            //{
            //    WebRefVal1.ReadOnly = false;
            //}
            //else
            //{
            //    WebRefVal1.ReadOnly = true;
            //}
            Calendar1.DataBind();

            MasterPage_MasterPage mpg = (MasterPage_MasterPage)this.Page.Master;
            mpg.HelpHref = "~/Help/WorkTime/查阅本人考勤.htm";
            mpg.PageName = "查看员工的月考勤";
            mpg.PicUrl = "";
            mpg.IntiBar();
        }
        else
        {
            string ss = SelUser.EmployeeId.ToString();
            if (ss.Length > 0) EmpId = ss;
            //Calendar1.DataBind();
        }
    }


    protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
    {

        if ((FirstDayOfThisMonth <= e.Day.Date) && (LastDayOfThisMonth >= e.Day.Date))
        {
            e.Cell.VerticalAlign = VerticalAlign.Top;
            string DKey = e.Day.Date.Year.ToString().Trim() + "-" + e.Day.Date.Month.ToString().Trim() + "-" + e.Day.Date.Day.ToString().Trim();
            bool NowIsWorkingDay = IsWorkingDay(e.Day.Date);
            int OverTimeHours = 0;

            if (EmpOverTimeDateTable.ContainsKey(DKey))
            {
                object[] DtIn = (object[])EmpOverTimeDateTable[DKey];
                OverTimeHours = (int)DtIn[2];
            }

            if (NowIsWorkingDay == false) //非工作日
            {
                if (EmpWorkOnDateTable.ContainsKey(DKey))
                {

                    DateTime[] DtIn = (DateTime[])EmpWorkOnDateTable[DKey];
                    string Sk1 = DtIn[0].Hour.ToString(".##") + ":" + DtIn[0].Minute.ToString(".##");
                    string Sk2 = DtIn[1].Hour.ToString(".##") + ":" + DtIn[1].Minute.ToString(".##");
                    Single WorkHour0 = 0;
                    int IsAbsence = IsWorkingAbsence(DKey, DtIn[0], DtIn[1], out WorkHour0);
                    string ShowText = "<p>";
                    //ShowText = ShowText + string.Format("{0}~{1}", Sk1, Sk2);
                    if (WorkHour0 > 0.5) ShowText = ShowText + string.Format("有考勤{0}", WorkHour0.ToString(".##"));// Sk1, Sk2);
                    if (OverTimeHours > 0) ShowText = ShowText + string.Format("+加班{0}", OverTimeHours.ToString(".##"));
                    ShowText = ShowText + "小时</p>";
                    e.Cell.Controls.Add(new LiteralControl(ShowText));
                    e.Cell.BorderColor = System.Drawing.Color.Black;
                    e.Cell.BorderWidth = 1;
                    e.Cell.BorderStyle = BorderStyle.Solid;
                    e.Cell.BackColor = System.Drawing.Color.Tomato;
                }
                else
                {
                    string ShowText = "<p>";
                    if (OverTimeHours > 0) ShowText = ShowText + string.Format("+加班{0}小时", OverTimeHours.ToString(".##"));
                    ShowText = ShowText + "</p>";
                    e.Cell.Controls.Add(new LiteralControl(ShowText));
                    e.Cell.BorderColor = System.Drawing.Color.Black;
                    e.Cell.BorderWidth = 1;
                    e.Cell.BorderStyle = BorderStyle.Solid;
                    e.Cell.BackColor = System.Drawing.Color.Tomato;
                }
            }
            else  //工作日
            {
                if (EmpWorkOnDateTable.ContainsKey(DKey))
                {
                    DateTime[] DtIn = (DateTime[])EmpWorkOnDateTable[DKey];
                    Single WorkHour = 0;
                    int IsAbsence = IsWorkingAbsence(DKey, DtIn[0], DtIn[1], out WorkHour);
                    if (IsAbsence == 0)//否缺迟到,早退
                    {
                        string Sk1 = DtIn[0].Hour.ToString(".##") + ":" + DtIn[0].Minute.ToString(".##");
                        string Sk2 = DtIn[1].Hour.ToString(".##") + ":" + DtIn[1].Minute.ToString(".##");

                        string ShowText = "<p>";
                        ShowText = ShowText + "正常";// string.Format("{0}~{1}", Sk1, Sk2);
                        if (OverTimeHours > 0) ShowText = ShowText + string.Format("+加班{0}小时", OverTimeHours.ToString(".##"));
                        ShowText = ShowText + "</p>";

                        e.Cell.Controls.Add(new LiteralControl(ShowText));
                        e.Cell.BorderColor = System.Drawing.Color.Black;
                        e.Cell.BorderWidth = 1;
                        e.Cell.BorderStyle = BorderStyle.Solid;
                        e.Cell.BackColor = System.Drawing.Color.LightGray;
                    }
                    else
                    {
                        TimeSpan NTd = (DtIn[1] - DtIn[0]);
                        Single LeaveHour = 0;
                        Single Evection = 0;
                        Single OutHour = 0;
                        int Dtyp = (int)WorkingOutTime(EmpId, DKey, out   LeaveHour, out Evection, out OutHour);
                        Single Dhour = WorkHour + LeaveHour + Evection + OutHour;

                        string Sk1 = DtIn[0].Hour.ToString(".##") + ":" + DtIn[0].Minute.ToString(".##");
                        string Sk2 = DtIn[1].Hour.ToString(".##") + ":" + DtIn[1].Minute.ToString(".##");
                        string ShowText = "<p>";
                        if (WorkHour > 0.5) ShowText = ShowText + string.Format("有考勤{0}", WorkHour.ToString(".##"));// Sk1, Sk2);
                        if (OverTimeHours > 0) ShowText = ShowText + string.Format("+加班{0}", OverTimeHours.ToString(".##"));
                        if (LeaveHour > 0.5) ShowText = ShowText + string.Format("+请假{0}", LeaveHour.ToString(".##"));
                        if (Evection > 0.5) ShowText = ShowText + string.Format("+出差{0}", Evection.ToString(".##"));
                        if (OutHour > 0.5) ShowText = ShowText + string.Format("+公出{0}", OutHour.ToString(".##"));
                        ShowText = ShowText + "小时</p>";

                        //if ((LeaveHour + Evection + OutHour) > 0.5)
                        //{
                        //    ShowText = ShowText + "小时</p>";
                        //}
                        //else
                        //{
                        //    ShowText = ShowText + "小时</p>";
                        //}

                        if (Dhour < 8) //缺工作时间
                        {
                            e.Cell.Controls.Add(new LiteralControl(ShowText));
                            e.Cell.BorderColor = System.Drawing.Color.Black;
                            e.Cell.BorderWidth = 1;
                            e.Cell.BorderStyle = BorderStyle.Solid;
                            e.Cell.BackColor = System.Drawing.Color.GreenYellow;
                        }
                        else
                        {
                            e.Cell.Controls.Add(new LiteralControl(ShowText));
                            e.Cell.BorderColor = System.Drawing.Color.Black;
                            e.Cell.BorderWidth = 1;
                            e.Cell.BorderStyle = BorderStyle.Solid;
                            e.Cell.BackColor = System.Drawing.Color.LightGray;
                        }

                    }
                }
                else
                {
                    Single LeaveHour = 0;
                    Single Evection = 0;
                    Single OutHour = 0;
                    int Dtyp = (int)WorkingOutTime(EmpId, DKey, out   LeaveHour, out Evection, out OutHour);
                    Single Dhour = LeaveHour + Evection + OutHour;
                    string ShowText = "<p>";
                    if (OverTimeHours > 0) ShowText = ShowText + string.Format("+加班{0}", OverTimeHours.ToString(".##"));
                    if (LeaveHour > 0.5) ShowText = ShowText + string.Format("请假{0}", LeaveHour.ToString(".##"));
                    if (Evection > 0.5) ShowText = ShowText + string.Format("+出差{0}", Evection.ToString(".##"));
                    if (OutHour > 0.5) ShowText = ShowText + string.Format("+公出{0}", OutHour.ToString(".##"));
                    if (Dhour > 0.5)
                    {
                        ShowText = ShowText + "小时</p>";
                    }
                    else
                    {
                        ShowText = ShowText + "无考勤记录</p>";

                    }

                    e.Cell.Controls.Add(new LiteralControl(ShowText));
                    e.Cell.BorderColor = System.Drawing.Color.Black;
                    e.Cell.BorderWidth = 1;
                    e.Cell.BorderStyle = BorderStyle.Solid;
                    if (Dhour > 7.8)
                    {
                        e.Cell.BackColor = System.Drawing.Color.LightGray;
                    }
                    else
                    {
                        e.Cell.BackColor = System.Drawing.Color.Yellow;
                    }
                }
            }
        }
    }


    /// <summary>
    /// 取得本月某员工的的考勤和公司日期定义日的集合
    /// </summary>
    /// <param name="EmpId">员工工号</param>
    /// <param name="DateS">本月起始日</param>
    /// <param name="DataE">本月终止日</param>
    private void GetData(string EmpId, string DateS, string DataE)
    {
        StartWorkOn = ConfigurationManager.AppSettings["StartTimeOfWorkOnTime"];
        EndWorkOn = ConfigurationManager.AppSettings["EndTimeOfWorkOnTime"];
        LateOfStartTime = ConfigurationManager.AppSettings["LateOfStartTime"];
        LeaveOfEndTime = ConfigurationManager.AppSettings["LeaveOfEndTime"];

        object[] objParam = new object[3];
        objParam[0] = EmpId;
        objParam[1] = DateS;
        objParam[2] = DataE;
        object[] myRet = CliUtils.CallMethod("SWorkTime", "GetEmpWorkOnDateTable", objParam);
        if (myRet != null && (int)myRet[0] == 0)
        {
            EmpWorkOnDateTable = (Hashtable)myRet[1];
        }

        object[] objParam2 = new object[2];
        objParam2[0] = DateS;
        objParam2[1] = DataE;
        object[] myRet2 = CliUtils.CallMethod("SWorkTime", "GetCompWorkDateDefine", objParam2);
        if (myRet2 != null && (int)myRet2[0] == 0)
        {
            CompWorkDateDefine = (Hashtable)myRet2[1];
        }

        object[] objParam3 = new object[3];
        objParam3[0] = EmpId;
        objParam3[1] = DateS;
        objParam3[2] = DataE;
        object[] myRet3 = CliUtils.CallMethod("SWorkTime", "GetEmpWorkOvertimeDate", objParam);
        if (myRet3 != null && (int)myRet3[0] == 0)
        {
            EmpOverTimeDateTable = (Hashtable)myRet3[1];
        }

    }

    /// <summary>
    /// 取得某一日期下外出,请假,出差的时间
    /// </summary>
    /// <param name="DayKey">某一日期</param>
    /// <param name="DayHour">返回的时间数</param>
    /// <returns>返回外出的类型:请假=1,出差=2,公出=3</returns>
    private int WorkingOutTime(string EmpId, string DayKey, out Single LeaveHour, out Single Evection, out Single OutHour)
    {
        Single LeaveHourN = 0;
        Single EvectionN = 0;
        Single OutHourN = 0;
        DataSet EmpLeaveDate;
        object[] objParam = new object[2];
        objParam[0] = EmpId;
        objParam[1] = DayKey;//"2008-8-1";
        object[] myRet3 = CliUtils.CallMethod("SWorkTime", "GetEmpLeaveDate", objParam);
        int RDtyp = 0;

        if (myRet3 != null && (int)myRet3[0] == 0)
        {
            EmpLeaveDate = (DataSet)myRet3[1];
            //?EmpHs3.Tables[0].Rows.Count
            if (EmpLeaveDate.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < EmpLeaveDate.Tables[0].Rows.Count; i++)
                {
                    int DTyp = (int)EmpLeaveDate.Tables[0].Rows[i]["DTyp"];
                    RDtyp = DTyp;
                    switch (DTyp)
                    {
                        case 1: // do -- WorkTime_Leave
                            DateTime DateS = (DateTime)EmpLeaveDate.Tables[0].Rows[i]["DateFrom"];
                            DateTime DateE = (DateTime)EmpLeaveDate.Tables[0].Rows[i]["DateTo"];
                            LeaveHourN = LeaveHourN + GetDateDayDiff(DayKey, DateS, DateE);
                            break;
                        case 2: // do -- WorkTime_Evection
                            DateTime DateS2 = (DateTime)EmpLeaveDate.Tables[0].Rows[i]["DateFrom"];
                            DateTime DateE2 = (DateTime)EmpLeaveDate.Tables[0].Rows[i]["DateTo"];
                            EvectionN = EvectionN + GetDateDayDiff(DayKey, DateS2, DateE2);
                            break;
                        case 3: // do -- WorkTime_Out
                            int Dsh = (int)EmpLeaveDate.Tables[0].Rows[i]["OutHour"];
                            int DsM = (int)EmpLeaveDate.Tables[0].Rows[i]["OutSecond"];
                            int DEh = (int)EmpLeaveDate.Tables[0].Rows[i]["BackHour"];
                            int DEM = (int)EmpLeaveDate.Tables[0].Rows[i]["BackSecond"];
                            OutHourN = OutHourN + (DEh - Dsh) + (DEM - DsM) / 60;
                            break;
                    }
                }
            }
        }

        if (LeaveHourN > 8) LeaveHourN = 8.0F;
        LeaveHour = LeaveHourN;
        if (EvectionN > 8) EvectionN = 8.0F;
        Evection = EvectionN;
        if (OutHourN > 8) OutHourN = 8.0F;
        OutHour = OutHourN;
        return RDtyp;
    }

    /// <summary>
    /// 取得某一日期下请假,出差的时间数
    /// </summary>
    /// <param name="DayKey">某一日期</param>
    /// <param name="DateS">请假,出差的起始时间</param>
    /// <param name="DateE">请假,出差的终止时间</param>
    /// <returns>请假,出差的时间数</returns>
    private Single GetDateDayDiff(string DayKey, DateTime DateS, DateTime DateE)
    {
        DateTime DateSS = DateTime.Parse(DayKey + " " + StartWorkOn);
        DateTime DateEE = DateTime.Parse(DayKey + " " + EndWorkOn);
        DateTime ltDateSS = DateTime.Parse(DayKey + " " + LateOfStartTime);
        DateTime ltDateEE = DateTime.Parse(DayKey + " " + LeaveOfEndTime);

        double Ret = 0;

        if (DateS <= ltDateSS && ltDateEE <= DateE) //1整天
        { return (Single)8; }
        else if (DateS <= DateSS && DateEE >= DateE)//
        {
            TimeSpan NTd = (DateE - DateSS);
            Ret = (Single)NTd.Hours + Convert.ToDouble(NTd.Minutes) / 60.0;
            if (Ret > 8) Ret = 8.0F;
            return (Single)Ret;

        }
        else if (DateS >= ltDateSS && ltDateEE >= DateE)//
        {
            TimeSpan NTd = (DateE - DateS);
            Ret = (Single)NTd.Hours + Convert.ToDouble(NTd.Minutes) / 60.0;
            if (Ret > 8) Ret = 8.0F;
            return (Single)Ret;

        }
        else if (DateS >= ltDateSS && ltDateEE <= DateE)//
        {
            TimeSpan NTd = (DateEE - DateS);
            Ret = (Single)NTd.Hours + Convert.ToDouble(NTd.Minutes) / 60.0;
            if (Ret > 8) Ret = 8.0F;
            return (Single)Ret;
        }
        else
        {
            return (Single)0;
        }
    }

    /// <summary>
    /// 判断是否工作日缺席(迟到,早退)
    /// </summary>
    /// <param name="DateS">开始时间</param>
    /// <param name="DateE">终止时间</param>
    /// <param name="DayHour">终止时间</param>
    /// <returns>返回外出的类型:迟到=1,早退=2,迟到+早退=3,0=正常</returns>
    private int IsWorkingAbsence(string DayKey, DateTime DateS, DateTime DateE, out Single DayHour)
    {
        DateTime DateSS = DateTime.Parse(DayKey + " " + LateOfStartTime);
        DateTime DateEE = DateTime.Parse(DayKey + " " + LeaveOfEndTime);

        DateTime MidDate = DateTime.Parse(DayKey + " " + "12:00");

        double Ret = 0;

        if (DateS > DateSS && DateEE < DateE) //迟到
        {
            DateTime StDateSS = DateTime.Parse(DayKey + " " + StartWorkOn);
            TimeSpan NTd = (DateS - StDateSS);
            Ret = (Single)8 - Convert.ToDouble(NTd.Hours) - Convert.ToDouble(NTd.Minutes) / 60;
            if (Ret < 0) Ret = 0;
            DayHour = (Single)Ret;
            return 1;
        }
        else if (DateS < DateSS && DateEE > DateE) //早退
        {
            DateTime StDateEE = DateTime.Parse(DayKey + " " + EndWorkOn);
            TimeSpan NTd = (StDateEE - DateE);
            Ret = (Single)8 - Convert.ToDouble(NTd.Hours) - Convert.ToDouble(NTd.Minutes) / 60.0;
            if (Ret < 0) Ret = 0;
            DayHour = (Single)Ret;
            if (DateE < MidDate) DayHour = DayHour + 0.5F;
            return 2;
        }
        else if (DateS > DateSS && DateEE > DateE) //迟到+早退
        {
            DateTime StDateSS = DateTime.Parse(DayKey + " " + StartWorkOn);
            DateTime StDateEE = DateTime.Parse(DayKey + " " + EndWorkOn);
            TimeSpan NTd = (DateS - StDateSS);
            TimeSpan NTd2 = (StDateEE - DateE);
            Ret = (Single)8 - Convert.ToDouble(NTd.Hours) - Convert.ToDouble(NTd.Minutes) / 60.0 - Convert.ToDouble(NTd2.Hours) - Convert.ToDouble(NTd2.Minutes) / 60;
            if (Ret < 0) Ret = 0;
            DayHour = (Single)Ret;
            if (DateE < MidDate) DayHour = DayHour + 0.5F;
            return 3;
        }
        else
        {
            DayHour = 8;
            return 0;
        }

    }

    /// <summary>
    /// 判断是否为工作日
    /// </summary>
    /// <param name="Inday"></param>
    /// <returns></returns>
    private bool IsWorkingDay(DateTime Inday)
    {
        string DKey = Inday.Year.ToString().Trim() + "-" + Inday.Month.ToString().Trim() + "-" + Inday.Day.ToString().Trim();
        if (Inday.DayOfWeek == DayOfWeek.Saturday || Inday.DayOfWeek == DayOfWeek.Sunday)
        {
            if (CompWorkDateDefine.ContainsKey(DKey) == false)
            {
                return false;
            }
            else
            {
                object[] DtIn = (object[])CompWorkDateDefine[DKey];// { DTyp, DatePrepty };
                bool Dbk = (bool)DtIn[0];
                return Dbk;
            }
        }
        else
        {
            if (CompWorkDateDefine.ContainsKey(DKey) == false)
            {
                return true;
            }
            else
            {
                object[] DtIn = (object[])CompWorkDateDefine[DKey];// { DTyp, DatePrepty };
                bool Dbk = (bool)DtIn[0];
                return Dbk;
            }
        }

    }


    protected void Calendar1_PreRender(object sender, EventArgs e)
    {

        string ss2 = SelUser.EmployeeId;
        if (ss2.Length > 0) EmpId = ss2;

        string ss = SelUser.EmpName;
        if (ss.Length == 0)
        {
            ss = Srvtools.CliUtils.GetValue("_UserName")[1].ToString();
        }
        Calendar1.Caption = string.Format("<h2>{0}的考勤</h2>", ss);

        DateTime Std = new DateTime(1900, 1, 1, 1, 1, 1);
        if (Calendar1.VisibleDate < Std)
        {
            Std = DateTime.Now;
        }
        else
        {
            Std = Calendar1.VisibleDate;
        }

        int year = Std.Year;
        int month = Std.Month;
        FirstDayOfThisMonth = new DateTime(year, month, 1);
        LastDayOfThisMonth = new DateTime(year, month, DateTime.DaysInMonth(year, month));

        string DateS = FirstDayOfThisMonth.Year.ToString().Trim() + "-" + FirstDayOfThisMonth.Month.ToString().Trim() + "-" + FirstDayOfThisMonth.Day.ToString().Trim();
        string DataE = LastDayOfThisMonth.Year.ToString().Trim() + "-" + LastDayOfThisMonth.Month.ToString().Trim() + "-" + LastDayOfThisMonth.Day.ToString().Trim();


        GetData(EmpId, DateS, DataE);
        //string Sk = Calendar1.VisibleDate.Year.ToString().Trim() + "-" + Calendar1.VisibleDate.Month.ToString().Trim() + "-" + Calendar1.VisibleDate.Day.ToString().Trim();


    }

    protected void QueryEmpData_Click(object sender, EventArgs e)
    {
        // Calendar1.Load();
    }
    
}
